<?php

/*
 * Copyright (C) 2014 Administrator.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
 * MA 02110-1301  USA
 */

class Wdmin extends Controller {

    const LIST_LIMIT = 100;
    const loginKeyK = '4s5mpxa';

    public function __construct($ControllerName, $Action, $QueryString) {
        parent::__construct($ControllerName, $Action, $QueryString);
        $this->loadModel('Db');
    }

    /**
     * 平台首页
     * @todo loginKey校验
     */
    public function index() {
        $this->loadModel('Secure');
        $this->loadModel('WdminAdmin');
        if (isset($_COOKIE['loginKey'])) {
            
        } else {
            header('Location:' . $this->root . '?/Wdmin/login');
            exit(0);
        }
        $this->show();
    }

    /**
     * ajax 获取登录二维码
     */
    public function ajaxLoginQrcode() {
        $ip = $this->getIp();
        // get token
        $loginCode = $this->Db->query("INSERT INTO `admin_login_code_token` (`ip`,`createtime`) VALUES ('$ip',NOW());");

        # echo "INSERT INTO `admin_login_code_token` (`ip`,`createtime`) VALUES ('$ip',NOW());";
        if ($loginCode == false) {
            $loginCode = $this->Db->query("SELECT tid FROM `admin_login_code_token` WHERE `ip` = '$ip';");
            $this->Db->query("UPDATE `admin_login_code_token` SET `used` = 0 WHERE `ip` = '$ip';");
            $loginCode = $loginCode[0]['tid'];
        }
        $loginCode = '8814' . $loginCode;
        $stoken = WechatSdk::getServiceAccessToken();
        # echo WechatSdk::getCQrcodeTicket($stoken, $loginCode, WechatSdk::QR_SCENE);
        $qrcodeImage = WechatSdk::getCQrcodeImage(WechatSdk::getCQrcodeTicket($stoken, $loginCode, WechatSdk::QR_SCENE));
        echo $qrcodeImage;
    }

    /**
     * ajax check login code scan status
     * perform++
     */
    public function checkLogin() {
        $this->loadModel('WdminAdmin');
        $admin_acc = $this->post('admin_acc');
        $admin_pwd = $this->post('admin_pwd');
        if ($this->Db->isExist('admin', 'admin_account', $admin_acc)) {
            $real_pwd = (object) $this->Db->getOneRow("SELECT * FROM `admin` WHERE `admin_account` = '$admin_acc';");
            if ($this->WdminAdmin->pwdCheck($real_pwd->admin_password, $admin_acc, $admin_pwd)) {
                // 校验成功
                $this->WdminAdmin->updateAdminState($this->getIp(), $real_pwd->id);
                $this->echoJson(array('status' => 1, 'loginKey' => $this->WdminAdmin->encryptToken($real_pwd->admin_ip_address, $real_pwd->id, $admin_pwd)));
            } else {
                // 失败
                $this->echoJson(array('status' => 0));
            }
        } else {
            // 失败
            $this->echoJson(array('status' => 0));
        }
    }

    /**
     * login page
     */
    public function login() {
        $this->Smarty->assign('rand', (int) rand(1, 3));
        $this->Smarty->assign('ip', $this->getIp());
        $this->show();
    }

    /**
     * 获取订单列表
     * ajaxLoadOrderlist
     */
    public function ajaxLoadOrderlist($Query) {
        global $config;
        $express = include dirname(__FILE__) . '/../config/express_code.php';
        !isset($Query->page) && $Query->page = 0;
        // where
        if (!isset($Query->status)) {
            $Query->status = 'payed';
            $WHERE = " WHERE status = '$Query->status' ";
        } else {
            if ($Query->status == 'all') {
                $WHERE = "";
            }
        }

        $_SQL_limit = $Query->page * self::LIST_LIMIT . "," . self::LIST_LIMIT;
        $SQL = sprintf("SELECT * FROM `orders`%sORDER BY `last_mod` DESC,`order_time` DESC LIMIT $_SQL_limit;", $WHERE, $Query->status);
        # echo $SQL;
        $orderList = $this->Db->query($SQL);

        /**
         * 加工
         */
        foreach ($orderList as $index => $order) {
            // address
            $address = $this->Db->query("SELECT * FROM `orders_address` WHERE order_id = $order[order_id];");
            $orderList[$index]['address'] = $address[0];
            $orderList[$index]['order_time'] = $this->Util->dateTimeFormat($orderList[$index]['order_time']);
            $orderList[$index]['last_mod'] = $this->Util->dateTimeFormat($orderList[$index]['last_mod']);
            $orderList[$index]['statusX'] = $config->orderStatus[$orderList[$index]['status']];
            $orderList[$index]['expressName'] = $express[$orderList[$index]['express_com']];
            // product info
            $orderList[$index]['data'] = $this->Db->query("SELECT catimg,`pi`.product_name,`pi`.product_id,`sd`.product_count,`sd`.product_discount_price FROM `orders_detail` sd LEFT JOIN `vproductinfo` pi on pi.product_id = sd.product_id WHERE `sd`.order_id = " . $order['order_id']);
        }

        $this->Smarty->assign('olistcount', count($orderList));
        $this->Smarty->assign('orderlist', $orderList);
        if ($Query->status == 'all') {
            $this->show('wdmin/ajaxloadorderlistall.tpl');
        } else {
            $this->show();
        }
    }

    /**
     * ajaxGetOrderCount
     */
    public function ajaxGetOrderCount() {
        $count = $this->Db->query('SELECT COUNT(*) AS `count` FROM `orders` WHERE `status` = "payed";');
        echo $count[0]['count'];
    }

    /**
     * ajaxGetPageViewData
     * @return json string
     */
    public function ajaxGetPageViewData() {
        $data = $this->Db->query("SELECT
	COUNT(id) AS count,
	DATE_FORMAT(time, '%H') AS dt
FROM
	pageview_records
WHERE
	to_days(time) = to_days(now())
GROUP BY
	DATE_FORMAT(time, '%H') ORDER BY time DESC;");
        $dataX = range(0, 23);

        foreach ($dataX as $index) {
            $dataY[$index] = 0;
        }

        foreach ($data as $d) {
            $dataY[(int) $d['dt']] = (int) $d['count'];
        }

        // 访问量
        $monthStat = $this->Db->query("SELECT COUNT(*) AS count FROM pageview_records WHERE DATE_FORMAT(time,'%Y%m') = DATE_FORMAT(CURDATE(),'%Y%m');");
        $dayStat = $this->Db->query("SELECT COUNT(*) AS count FROM pageview_records WHERE to_days(time) = to_days(now());");

        $this->echoJson(array(
            'x' => $dataX,
            'y' => $dataY,
            'montot' => $monthStat[0]['count'],
            'daytot' => $dayStat[0]['count']
        ));
    }

    /**
     * ajaxLoadSaleHisCartData
     * 获取报表 单日销售记录
     * @return json string
     */
    public function ajaxLoadSaleHisCartData() {
        $mKey = 'fd208fc2a521a7153e1e66ca3a0b4b39';
        $this->loadModel('mMemcache');
        $json = $this->mMemcache->get($mKey);
        if ($json) {
            die($json);
        } else {
            $QueryMonth = date("Y-m");

            $data = $this->Db->query("SELECT * FROM `vstatdaysalesumraw` WHERE DATE_FORMAT(`day`,'%Y-%m') = '$QueryMonth' ORDER BY `day` DESC;");

            $dataX = array();
            $dataY = array();
            foreach ($data as $d) {
                $dataY[] = (float) $d['sum'];
                $dataX[] = $d['day'];
            }

            $dataX = array_reverse($dataX);
            $dataY = array_reverse($dataY);

            $json = $this->toJson(array(
                'x' => $dataX,
                'y' => $dataY
            ));

            $this->mMemcache->set($mKey, $json);

            echo $json;
        }
    }

    public function text() {
        $this->loadModel('WechatSdk');
        $slist = WechatSdk::getWechatSubscriberList(WechatSdk::getServiceAccessToken());

        $count = 0;

        foreach ($slist['data']['openid'] as $sob) {
            $count ++;
            $this->Db->query("REPLACE INTO wechat_subscribe_record (openid,dv) VALUES ('$sob',1);");
        }

        echo $count;
    }

    public function GmessList() {
        global $config;
        $list = $this->Db->query(sprintf("SELECT * FROM `gmess_page` WHERE `gmess_page`.`appid` = '%s' ORDER BY `createtime` DESC;", APPID));
        foreach ($list as &$l) {
            $l['href'] = "http://" . $this->server('HTTP_HOST') . "$config->shoproot?/Gmess/view/id=" . $l['id'];
        }
        $this->Smarty->assign('list', $list);
        $this->show();
    }

}
